package statement;

import bean.User;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.Scanner;

public class StatementTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String name = scanner.nextLine();
        System.out.println("请输入密码：");
        String password = scanner.nextLine();

        String sql = "SELECT id, name, password, adress, phone FROM user WHERE name='"+ name + "' AND password='" + password +"'";
        System.out.println(sql);

        User user = null;
        user = getInstantce(sql, User.class);
        System.out.println(user);
    }

    public static <T> T getInstantce(String sql, Class<T> className){
        T t = null;
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/java_jdbc?useUnicode=true&characterEncoding=utf8&useSSL=false";
        String user = "root";
        String password = "123456";

        try {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, user, password);

            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            ResultSetMetaData metaData = resultSet.getMetaData();

            int columnCount = metaData.getColumnCount();
            System.out.println(columnCount);

            if (resultSet.next()){
                t = className.newInstance();

                for (int i = 0; i < columnCount; i++) {
                    // 获取列名
                    String columnName = metaData.getColumnName(i + 1);
                    // 获取别名
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    // 获取列名对应的数据 字段值
                    Object object = resultSet.getObject(columnName);

                    //　使用反射赋值到对象
                    Field declaredField = className.getDeclaredField(columnName);
                    declaredField.setAccessible(true);
                    declaredField.set(t, object);
                }
            }
        } catch (ClassNotFoundException | SQLException | IllegalAccessException | InstantiationException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return t;
    }
}
